// src/image/image.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ImageEntity } from './entities/image.entity';
import { CreateImageDto } from './dto/create-image.dto';
import { promisify } from 'util';
import { stat } from 'fs';
import { join } from 'path';
import sizeOf from 'image-size';
import { readFileSync } from 'fs';
@Injectable()
export class ImageService {
  constructor(
    @InjectRepository(ImageEntity)
    private imageRepo: Repository<ImageEntity>
  ) {}

  async getPaginatedList(page: number, pageSize: number): Promise<{ total: number; list: ImageEntity[] }> {
    const [list, total] = await this.imageRepo.findAndCount({
      skip: (page - 1) * pageSize,
      take: pageSize,
      order: { id: 'DESC' }
    });

    return { list, total };
  }

  async create(dto: CreateImageDto): Promise<ImageEntity> {
    const image = this.imageRepo.create(dto);
    return this.imageRepo.save(image);
  }

async handleUpload(file: Express.Multer.File): Promise<ImageEntity> {
  const filePath = join(process.cwd(), 'uploads', file.filename);
  const buffer = readFileSync(filePath); // 读取为 Buffer
  const dimensions = sizeOf(buffer);     // 正确传入 Buffer

  const image = this.imageRepo.create({
    width: dimensions.width,
    height: dimensions.height,
    src: `/uploads/${file.filename}`
  });

  return this.imageRepo.save(image);
}
}
